package com.example.finalproject.experiments.sqlite

import android.content.ContentValues
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.example.finalproject.ui.theme.FinalProjectTheme

class SQLiteExperimentActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            FinalProjectTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    UserDatabaseScreen()
                }
            }
        }
    }
}

@Composable
fun UserDatabaseScreen() {
    val context = LocalContext.current
    val dbHelper = remember { UserDatabaseHelper(context) }
    var username by remember { mutableStateOf("") }
    var hobby by remember { mutableStateOf("") }
    var userList by remember { mutableStateOf(listOf<Triple<Int, String, String>>()) }
    var showDialog by remember { mutableStateOf(false) }
    var deleteId by remember { mutableStateOf(-1) }

    fun queryUsers() {
        val db = dbHelper.readableDatabase
        val cursor = db.query(UserDatabaseHelper.TABLE_NAME, null, null, null, null, null, null)
        val list = mutableListOf<Triple<Int, String, String>>()
        while (cursor.moveToNext()) {
            val id = cursor.getInt(cursor.getColumnIndexOrThrow(UserDatabaseHelper.COL_ID))
            val name = cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseHelper.COL_USERNAME))
            val hob = cursor.getString(cursor.getColumnIndexOrThrow(UserDatabaseHelper.COL_HOBBY))
            list.add(Triple(id, name, hob))
        }
        cursor.close()
        userList = list
    }

    LaunchedEffect(Unit) { queryUsers() }

    Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
        Text(text = "用户名")
        OutlinedTextField(
            value = username,
            onValueChange = { username = it },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Text(text = "爱好")
        OutlinedTextField(
            value = hobby,
            onValueChange = { hobby = it },
            modifier = Modifier.fillMaxWidth()
        )
        
        Spacer(modifier = Modifier.height(8.dp))
        
        Row {
            Button(
                onClick = {
                    if (username.isNotBlank() && hobby.isNotBlank()) {
                        val db = dbHelper.writableDatabase
                        val values = ContentValues().apply {
                            put(UserDatabaseHelper.COL_USERNAME, username)
                            put(UserDatabaseHelper.COL_HOBBY, hobby)
                        }
                        db.insert(UserDatabaseHelper.TABLE_NAME, null, values)
                        username = ""
                        hobby = ""
                        queryUsers()
                        Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show()
                    } else {
                        Toast.makeText(context, "请填写完整信息", Toast.LENGTH_SHORT).show()
                    }
                }
            ) {
                Text("添加用户")
            }
            
            Spacer(modifier = Modifier.width(8.dp))
            
            Button(
                onClick = { queryUsers() }
            ) {
                Text("刷新列表")
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        LazyColumn {
            items(userList) { (id, name, hob) ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp)
                        .clickable {
                            deleteId = id
                            showDialog = true
                        }
                ) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        Text(text = "用户名：$name")
                        Text(text = "爱好：$hob")
                    }
                }
            }
        }
    }

    if (showDialog) {
        AlertDialog(
            onDismissRequest = { showDialog = false },
            title = { Text("确认删除") },
            text = { Text("确定要删除这条记录吗？") },
            confirmButton = {
                TextButton(
                    onClick = {
                        val db = dbHelper.writableDatabase
                        db.delete(
                            UserDatabaseHelper.TABLE_NAME,
                            "${UserDatabaseHelper.COL_ID} = ?",
                            arrayOf(deleteId.toString())
                        )
                        showDialog = false
                        queryUsers()
                        Toast.makeText(context, "删除成功", Toast.LENGTH_SHORT).show()
                    }
                ) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = { showDialog = false }
                ) {
                    Text("取消")
                }
            }
        )
    }
}